<?php

// 报表

class reportControlPage extends commonControlPage {

    private $cur_uid = 0;

    public function __construct() {
        parent::__construct();

        $this->view->addScript('rili');
        $this->view->addScript('autocomplete');

        if ($_REQUEST['q']!=NULL) {
            if (AJAX) {
                $users = $_ENV['db']->fetchAll("SELECT * FROM admincp_member WHERE username LIKE '%{$_REQUEST['q']}%'");
                echo json_encode($users);
                exit;
            } else {
                $uid = $_ENV['db']->fetchCol("SELECT uid FROM admincp_member WHERE `username` = '{$_REQUEST['q']}'");
                if (!$uid) $this->showMessage('未找到用户'.$_REQUEST['q'],'back');

                $this->cur_uid = $uid;
                $this->view->search_user = $_REQUEST['q'];
            }
        }
    }

    private function checkDateFormat() {
        $start_date = $_POST['start_date'];
        $end_date = $_POST['end_date'];

        if (!ValidateDate($start_date) || !ValidateDate($end_date)) {
            $this->showMessage('日期格式错误','back');
        }

        $start_date = strtotime($start_date);
        $end_date = strtotime($end_date." 23:59:59");

        if ($start_date > $end_date) {
            $this->showMessage('结束时间必须小于开始时间','back');
        }

        if (($end_date-$start_date) > 31536000) {
            $this->showMessage('所选日期时间段超过了1年','back');
        }

        return array('s'=>$start_date,'e'=>$end_date);
    }

    private function getDates($dateline1,$dateline2,$type='m') {
        set_time_limit(5);
        if ($type == 'm') {
            $f = '+ 1 month';
            $sp = 'Y-m';
        } else if($type == 'd') {
            $f = '+ 1 day';
            $sp = 'm-d';
        } else if($type == 'z') {
        }

        $end = date($sp,$dateline2);
        $start = date($sp,$dateline1);

        if ($start >= $end) {
            return array();
        }

        $dates = array();
        $dateline = $dateline1;

        do {
            $date = date($sp,$dateline);
            $dates[] = $date;
            if ($date == $end) {
                break;
            } else {
                $dateline = strtotime($f,$dateline);
            }
        }while(true);

        return array('dates'=>$dates,'sp'=>$sp,'f'=>$f);
    }

    ## 费用
    public function feiyongModule() {
        if (POST) {
            $date = $this->checkDateFormat();
            $start_date = $date['s'];
            $end_date = $date['e'];
echo "http://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}&s={$start_date}&e={$end_date}&act=json&q={$_REQUEST['q']}&r=".microtime();exit;
            $this->view->data_url = urlencode("http://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}&s={$start_date}&e={$end_date}&act=json&q={$_REQUEST['q']}&r=".microtime());
        }

        if (!empty($_GET['s']) && !empty($_GET['e']) && $_GET['act'] == 'json') {
            $chart = new class_chart();

            $cfg = $this->getDates($_GET['s'],$_GET['e'],'d');
            $dates = $cfg['dates'];
            $sp = $cfg['sp'];
            $f  = $cfg['f'];

            $where = '1';

            if (!empty($_GET['q'])) {
                $where .= ' and uid = '.$this->cur_uid;
                $chart->setTitle("{$_GET['q']}的费用报表");
            } else {
                $chart->setTitle("天高智慧费用报表");
            }

            $where .= ' and audit2_dateline between '.$_GET['s'].' and '.$_GET['e'];

            $rows = $_ENV['db']->fetchAll("SELECT * FROM daily where {$where}");
            
            $traffic = $live = $other = array();
            foreach ($rows as $item) {
                $date = date($f,$item['audit2_dateline']);
                $traffic[$date]+=$item['traffic_subtotal'];
                $live[$date] +=$item['live_subtotal'];
                $other[$date]+=$item['other_subtotal'];
            }

            foreach ($dates as $val) {
                if(!isset($traffic[$val])) $traffic[$val] = 0;
                if(!isset($live[$val])) $live[$val] = 0;
                if(!isset($other[$val])) $other[$val] = 0;
            }
            
            $chart->setLabels($dates);
            $chart->addElement('交通费用总计','#334455',array_values($traffic));
            $chart->addElement('住宿费用总计','#009393',array_values($live));
            $chart->addElement('其他费用总计','#4B0091',array_values($other));

            echo $chart->getJson();
            exit;
        }

        $this->showMainPage("admincp/report");
    }

    ## 请假
    public function qingjiaModule() {
        if (POST) {
            $date = $this->checkDateFormat();
            $start_date = $date['s'];
            $end_date = $date['e'];

            $this->view->data_url = urlencode("http://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}&s={$start_date}&e={$end_date}&act=json&q={$_REQUEST['q']}&r=".microtime());
        }

        if (!empty($_GET['s']) && !empty($_GET['e']) && $_GET['act']=='json') {
            $chart = new class_chart();

            $where = '1';

            if (!empty($_GET['q'])) {
                $where .= ' and uid = '.$this->cur_uid;
                $chart->setTitle("{$_GET['q']}的请假报表");
            } else {
                $chart->setTitle("天高智慧请假报表");
            }

            $where .= ' and audit2_dateline between '.$_GET['s'].' and '.$_GET['e'];

            $rows = $_ENV['db']->fetchAll("SELECT * FROM vacation where {$where}");

            $total = $month = array();

            foreach ($rows as $item) {
                $date = date('Y-m',$item['audit2_dateline']);
                if (!in_array($date,$month)) $month[] = $date;

                $total[$date]+=1;
            }
            
            $chart->setLabels($month);
            $chart->addElement('请假次数','#334455',array_values($total));

            echo $chart->getJson();
            exit;
        }

        $this->showMainPage("admincp/report");
    }

    ## 借款
    public function jiekuanModule() {
        if (POST) {
            $date = $this->checkDateFormat();
            $start_date = $date['s'];
            $end_date = $date['e'];

            $this->view->data_url = urlencode("http://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}&s={$start_date}&e={$end_date}&act=json&q={$_REQUEST['q']}&r=".microtime());
        }

        if (!empty($_GET['s']) && !empty($_GET['e']) && $_GET['act']=='json') {
            $chart = new class_chart();

            $where = '1';

            if (!empty($_GET['q'])) {
                $where .= ' and uid = '.$this->cur_uid;
                $chart->setTitle("{$_GET['q']}的借款报表");
            } else {
                $chart->setTitle("天高智慧借款报表");
            }

            $where .= ' and audit2_dateline between '.$_GET['s'].' and '.$_GET['e'];

            $rows = $_ENV['db']->fetchAll("SELECT * FROM loan where {$where}");

            $times = $loan = $arr = $month = array();

            foreach ($rows as $item) {
                $date = date('Y-m',$item['audit2_dateline']);
                if (!in_array($date,$month)) $month[] = $date;

                ## 次数
                $times[$date]+=1;
                ## 借款金额
                $loan[$date]+=$item['price'];
            }
            
            $chart->setLabels($month);
            $chart->addElement('借款次数','#334455',array_values($times));
            $chart->addElement('借款金额','#eeddff',array_values($loan));

            echo $chart->getJson();
            exit;
        }

        $this->showMainPage("admincp/report");
    }

    ## 采购
    public function caigouModule() {
        if (POST) {
            $date = $this->checkDateFormat();
            $start_date = $date['s'];
            $end_date = $date['e'];

            $this->view->data_url = urlencode("http://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}&s={$start_date}&e={$end_date}&act=json&q={$_REQUEST['q']}&r=".microtime());
        }

        if (!empty($_GET['s']) && !empty($_GET['e']) && $_GET['act']=='json') {
            $chart = new class_chart();

            $where = '1';

            if (!empty($_GET['q'])) {
                $where .= ' and uid = '.$this->cur_uid;
                $chart->setTitle("{$_GET['q']}的采购报表");
            } else {
                $chart->setTitle("天高智慧采购报表");
            }

            $where .= ' and created_time between '.$_GET['s'].' and '.$_GET['e'];

            $rows = $_ENV['db']->fetchAll("SELECT * FROM product_stock_history where {$where}");

            $times = $num = $price = $month = array();

            foreach ($rows as $item) {
                $date = date('Y-m',$item['created_time']);
                if (!in_array($date,$month)) $month[] = $date;

                ## 次数
                $times[$date]+=1;
                ## 采购数量
                $num[$date]+=$item['num'];
                ## 采购价格
                $price[$date]+=$item['price'];
            }
            
            $chart->setLabels($month);
            $chart->addElement('采购次数','#000000',array_values($times));
            $chart->addElement('总采购数量','#548C00',array_values($num));
            $chart->addElement('总采购金额','#5151A2',array_values($price));

            echo $chart->getJson();
            exit;
        }

        $this->showMainPage("admincp/report");
    }

    ## 利润
    public function lirunModule() {
        if (POST) {
            $date = $this->checkDateFormat();
            $start_date = $date['s'];
            $end_date = $date['e'];

            $this->view->data_url = urlencode("http://{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}&s={$start_date}&e={$end_date}&act=json&r=".microtime());
        }
        #1.按照公式进行计算
        if ($_GET['act'] == 'json' && !empty($_GET['s']) && !empty($_GET['e'])) {

            $products = $_ENV['db']->fetchAll("SELECT p.num,p.aprice,p.bnum,p.bprice,od.product_num as buynum,o.last_time as ltime,o.pprice FROM order_detail as od LEFT JOIN product as p ON od.product_id = p.product_id LEFT JOIN `order` as o ON od.order_id = o.order_id WHERE o.audit_state = 8 and o.last_time between ".(int)$_GET['s']." and ".(int)$_GET['e']);

            $month = $lirun = $chengben = $pprice = array();

            foreach ((array)$products as $product) {
                $date = date('Y-m',$product['ltime']);
                
                if (!in_array($date,$month)) $month[] = $date;
                
                if ($product['buynum'] > $product['num']) {
                    $t_chengben = ($product['buynum']-$product['num'])*$product['aprice'] + $product['bprice']*$product['bnum'];
                } else {
                    $t_chengben = $product['buynum']*$product['aprice'] + $product['bprice']*$product['bnum'];
                }
                
                // 当前月总成本
                $chengben[$date]+=$t_chengben;
                // 当前月总利润
                $lirun[$date]+=$product['pprice']-$t_chengben;
                $pprice[$date]+=$product['pprice'];
            }

            $chart = new class_chart();
            $chart->setTitle('天高智慧');
            $chart->setLabels($month);
            if ($chengben && $lirun) {
                $chart->addElement('总成本金额','#9933CC',array_values($chengben));
                $chart->addElement('总利润金额','#66aadd',array_values($lirun));
                $chart->addElement('毛利润','#aa8833',array_values($pprice));
            }
            echo $chart->getJson();
            exit;
        }
        #2.统计畅销商品
        $this->showMainPage('admincp/report');
    }
}